from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
# Create your views here.

def addcourse(request):
    print('添加成功')
    return JsonResponse({"code":200})

# 部门接口
class DeptmentView(APIView):
    def get(self,request):
        # 获取所有数据
        dep = Department.objects.all()
        deplist = [{"id":i.id,"name":i.name} for i in dep]
        return Response({'code':200,'deplist':deplist})

    def post(self,request):
        # 获取参数
        data = request.data
        try:
            name = data['name']
        except:
            return Response({'code':10010,'mes':'必须输入name'})
        # 添加
        dept = Department(name = data['name'])
        dept.save()
        # 返回结果
        return Response({'code':200})

# 员工接口
class EmpView(APIView):
    def get(self,request):
        # 获取所有数据
        dep = Emp.objects.all()
        deplist = [{"id":i.id,"name":i.name,'deptid':i.dep.id,'dname':i.dep.name} for i in dep]
        return Response({'code':200,'deplist':deplist})

    def post(self,request):
        # 获取参数
        data = request.data
        try:
            name1 = data['name']
            age1 = data['age']
            dep1 = data['dep']
        except:
            return Response({'code':10010,'mes':'必须输入name'})
        # 添加
        dept = Emp(name=name1,age=age1,dep_id=dep1)
        dept.save()
        # 返回结果
        return Response({'code':200})

    # 修改
    def put(self,request):
        data = request.data
        try:
            name = data['name']
            age = data['age']
            dep = data['dep']
            id = data['id']
            # d = Department.objects.get(id=dep).first()
        except:
            return Response({'code':10010,'mes':'必须输入name'})
        # 添加
        dept = Emp.objects.filter(id=id).first()
        dept.name = name
        dept.age = age
        dept.dep_id = dep
        dept.save()
        dept = Emp.objects.filter(id=id).update(name=name,age=age)
        return Response({'code':200})